package com.cxyzy.demo.ext

import com.cxyzy.demo.BEARER
import com.cxyzy.demo.HTTP_HEADER_AUTH
import com.cxyzy.demo.interceptor.HttpHeaderInterceptor
import com.cxyzy.demo.interceptor.TokenInterceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor

fun getOkHttpClient(): OkHttpClient {
    return OkHttpClient.Builder()
            .apply {
                addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY })
                addInterceptor(HttpHeaderInterceptor())
                addInterceptor(TokenInterceptor())
            }.build()
}

fun addTokenInHeader(request: Request, token: String): Request {
    return request.newBuilder()
            .addHeader(HTTP_HEADER_AUTH, "$BEARER $token")
            .build()
}

fun replaceTokenInHeader(request: Request, token: String): Request {
    return request.newBuilder()
            .removeHeader(HTTP_HEADER_AUTH)
            .addHeader(HTTP_HEADER_AUTH, "$BEARER $token")
            .build()
}